package com.example.easycharge.service;

import com.alibaba.fastjson.JSONObject;
import com.example.easycharge.entity.ChargePile;
import com.example.easycharge.error.*;
import com.example.easycharge.notRepEntity.QueueStateEnum;
import com.example.easycharge.repository.ChargePileRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class PileService {
    @Autowired
    private ChargePileRepository chargePileRepository;
    @Autowired
    private ChargeService chargeService;

    public JSONObject addNewQueue(ChargePile pile) throws QueueExistError {
        JSONObject jsonObject = new JSONObject();
        long pileId = pile.getChargePileId();
        chargePileRepository.setPileActive(pileId);
        ChargePile chargePile = chargePileRepository.findChargePileByChargePileId(pileId);
        chargeService.addNewQueue(pile, pileId);
        jsonObject.put("message", "新增队列成功");
        return jsonObject;
    }

    public JSONObject removeQueue(long pileId) throws PileNotFoundError, ServiceNotSupport {
        JSONObject jsonObject = new JSONObject();
        chargePileRepository.setPileShutOff(pileId);
        chargeService.transVehicle(pileId);
        chargeService.removeQueue(pileId);
        jsonObject.put("message", "移除队列成功");
        return jsonObject;
    }

    public JSONObject deletePile(long pileId) {
        JSONObject jsonObject = new JSONObject();
        chargePileRepository.deleteById(pileId);
        jsonObject.put("message", "删除充电桩成功");
        return jsonObject;
    }

    public JSONObject setErrorPile(long pileId) throws PileNotFoundError, ServiceNotSupport {
        JSONObject jsonObject = new JSONObject();
        chargePileRepository.setPileError(pileId);
        // 将充电桩设置为故障后，需要移除充电桩
        chargeService.transVehicle(pileId);
        chargeService.removeQueue(pileId);
        jsonObject.put("message", "设置充电桩故障成功");
        return jsonObject;
    }

    public JSONObject setRecoveryPile(long pileId) throws PileNotFoundError, ServiceNotSupport, QueueExistError, BillNotFoundError, WithoutAuthorityError, QueueNotFoundError, InvalidOperateError {
        JSONObject jsonObject = new JSONObject();
        chargePileRepository.setPileRecovery(pileId);
        // 激活这个队列
        ChargePile chargePile = chargePileRepository.findChargePileByChargePileId(pileId);
        addNewQueue(chargePile);
        // 按照要求合并队列
        chargeService.recoveryQueue(pileId);
        jsonObject.put("message", "修复充电桩故障成功");
        return jsonObject;
    }

}
